<template>
  <form-view class="task-tab-container task-view-containner" :fields="taskfields" :value="planTask">
    <template slot="planNumber" slot-scope="{ field, value }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div class="form-view-row-content">{{ value }}</div>
      </div>
    </template>

    <template slot="name" slot-scope="{ field, value }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div class="form-view-row-content">{{ value }}</div>
      </div>
    </template>

    <template slot="state" slot-scope="{ field, value }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div class="form-view-row-content">{{ stateMap[value] }}</div>
      </div>
    </template>

    <template slot="templateName" slot-scope="{ }">
      <div class="form-view-row">
        <label>{{$t('common.task.taskType')}}</label>
        <div class="form-view-row-content">{{ task.templateName }}</div>
      </div>
    </template>

    <template slot="customer" slot-scope="{ field }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <!-- <span
          v-if="true"
          class="link-text"
          @click="openCustomerView(task.customer.id)"
        >{{ task.customer.name}}</span>
        <span v-else>{{ task.customer.name}}</span> -->
        <span>{{ task.customer.name}}</span>
      </div>

      <!-- start 产品 -->
      <template v-if="products.length > 0">
        <div class="form-view-row" v-if="!products.length"><label>{{$t('common.base.product')}}</label></div>
        <div class="product-list" v-else>
          <div class="product-item" v-for="(product, index) in products" :key="product.id">
            <div class="product-item-name">
              <label>{{$t('common.base.product')}}</label>
              <!-- <span
                class="link-text"
                :key="product.id"
                @click="openProductView(product.id)"
                v-if="!isEncryptField(product.name) && canSeeCustomer"
              >{{ product.name }}</span>
              <span v-else>{{ product.name }}</span> -->

              <span>{{ product.name }}</span>

              <!-- 关联任务数不展示 -->
              <el-tooltip v-if="showProductRelationCount(product) && canSeeCustomer && false" placement="top">
                <div slot="content" v-html="$t('task.detail.components.unfinishedAndAllTask', {unfinished: productRelationCount[product.id].unfinished, all: productRelationCount[product.id].all + archiveCountArr[index]})"></div>
                <div class="relation-count-button" @click="openProductView(product.id)">
                  {{ `${productRelationCount[product.id].unfinished}/${productRelationCount[product.id].all + archiveCountArr[index]}` }}
                </div>
              </el-tooltip>
            </div>
            <!-- 关联字段暂不展示 -->
            <div class="form-row-two-columns product-item-relation">
              <div class="form-view-row" v-for="field in relationProductfields" :key="field.id">
                <label>{{ field.displayName }}</label>
                <div class="form-view-row-content">
                  {{ product[field.fieldName] || ''}}
                </div>
                <!-- <div
                  v-if="(field.setting || {}).formType === 'cascader' && (field.setting || {}).isMulti"
                  class="form-view-row-content">
                  {{ (task.attribute[field.fieldName] || [])[index] | fmt_form_cascader((field.setting || {}).isMulti)}}
                </div>
                <div class="form-view-row-content" v-else> {{ prettyRelationProductValue(task.attribute[field.fieldName], index) }} </div> -->
              </div>
            </div>
          </div>
        </div>
      </template>
      <!-- end 产品 -->

      <!-- TODO: 临时解决客户字段设置产品未勾选时隐藏 -->
      <template v-else><div class="hide"></div></template>
    </template>

    <template slot="tlmName" slot-scope="{ field }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div class="form-view-row-content">{{ task.tlmName }}</div>
      </div>
    </template>

    <template slot="tlmPhone" slot-scope="{ field }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div class="form-view-row-content">{{ task.tlmPhone }}</div>
      </div>
    </template>

    <template slot="taddressStr" slot-scope="{ field }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div class="form-view-row-content">{{ address }}</div>
      </div>
    </template>

    <template slot="createRule" slot-scope="{ field, value }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div class="form-view-row-content">{{ value === 1 ? $t('task.edit.generateRules.multiple') : $t('task.edit.generateRules.single')}}</div>
      </div>
    </template>
    
    <template slot="headName" slot-scope="{ field }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div class="form-view-row-content">{{ getHeadName() }}</div>
      </div>
    </template>

    <template slot="period" slot-scope="{ field }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div class="form-view-row-content">{{ `${$t('common.base.per')}${planTask.periodSetting.period}${planTask.periodSetting.periodUnit}` }}</div>
      </div>
    </template>

    <!-- start 创建人 -->
    <template slot="createUser" slot-scope="{ field }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div v-if="planTask.createUserId" class="form-view-row-content">
          <span v-user="planTask.createUserId" class="user-card-triggle">
            <template v-if="isOpenData">
              <open-data type="userName" :openid="planTask.createUserStaffId"></open-data>
            </template>
            <template v-else>
              {{planTask.createUserName}}
            </template>   
          </span>
          <template v-if="isProviderManager && task.serviceProviderCreateName">
            <span>（{{task.serviceProviderCreateName}}）</span>
          </template>
        </div>
      </div>
    </template>
    <!-- end 创建人 -->

    <!-- start 创建时间 -->
    <template slot="createTime" slot-scope="{ field, value }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div class="form-view-row-content">{{ value | fmt_datetime }}</div>
      </div>
    </template>
    <!-- end 创建时间 -->

    <!-- start 截止时间 -->
    <template slot="end" slot-scope="{ field }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div class="form-view-row-content">{{ getEndTime() }}</div>
      </div>
    </template>
    <!-- end 截止时间 -->

    <!-- start 负责人 -->
    <template slot="executor" slot-scope="{ field, value }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div v-if="value" class="form-view-row-content">
          <span v-user="value.userId" class="user-card-triggle">
            <template v-if="isOpenData">
              <open-data type="userName" :openid="value.staffId"></open-data>
            </template>
            <template v-else>
              {{value.displayName}}
            </template>
          </span>
          <template v-if="isProviderManager && task.serviceProviderName">
            <span>（{{task.serviceProviderName}}）</span>
          </template>
        </div>
      </div>
    </template>
    <!-- end 负责人 -->

    <!-- start 派单设置 -->
    <template slot="dispatchSettings" slot-scope="{ field }">
      <div class="form-view-row">
        <label>{{ field.displayName }}</label>
        <div class="form-view-row-content">{{ getHeadName('dispatchSettings') }}</div>
      </div>
    </template>
    <!-- end 派单设置 -->

  </form-view>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';

/* enum */
import { TaskEventNameMappingEnum } from '@model/enum/EventNameMappingEnum.ts';
import { TaskCreateMethodLabelEnum } from '@model/enum/LabelEnum.ts';
import { isBasicEditionHideEvent } from '@shb-lib/version';
import { getCount } from '@src/api/ArchiveApi';
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'
import { chooseExUser } from '@model/config/SelectUserConfig.ts'
import { getRootWindow } from '@src/util/dom';
import { openTabForProductView, openTabForEventView } from '@src/util/business/openTab'

import { formatDate } from 'pub-bbx-utils'
import i18n from '@src/locales';

import Filter from '@src/filter/filter.js'

import { getProductRelation } from '@src/modules/task/taskTypes/planTask/view/fields'
import addressKeyToViewLanguage, { getCountryKey } from '@src/component/common/BaseAddressSwitch/addressNameMultiLanguage';

const ENCRYPT_FIELD_VALUE = '***';

export default {
  name: 'task-plan-view',
  props: {
    planTask: {
      type: Object,
      default: () => ({})
    },
    fields: {
      type: Array,
      default: () => ([])
    },
  },
  data() {
    return {
      isOpenData,
      task: this.planTask.task || {},

      stateMap: {
        0: i18n.t('common.task.type.processing'),
        1: i18n.t('common.task.type.finished'),
        2: i18n.t('common.task.type.offed')
      },

      products: this.buildProducts(),

      productRelationCount: {}, // 产品关联的工单数量
      archiveCountArr: [], // 归档工单数量
      address: '',
    }
  },
  computed: {
    canSeeCustomer() {
      return this.planTask.canSeeCus || true; // 后端不好加 先写死 二期优化
    },
    /** 
    * @description 工单自定义字段
    * 过滤产品关联字段，需给每个产品显示对应产品关联字段
    */
    taskfields() {
      const field_source_type = this.task?.attribute?.field_source_type === 'task'

      let fields = this.fields
      if(field_source_type) {
        fields = this.fields.filter(item => item.fieldName !== 'field_customer_separator')
      }
      
      return fields.filter(field => field.formType != 'relationProduct');
    },
    /** 
    * @description 产品关联字段
    */
    relationProductfields() {
      return getProductRelation()
      // return this.fields.filter(field => field.formType == 'relationProduct');
    },
    // 基础版功能隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent() 
    },
    // 是否开启服务商灰度
    isProviderManager() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.providerManager || false
    },
    archiveCount() {
      return this.archiveCountArr
    }
  },
  filters: {

  },
  methods: {
    // 负责人 + 派单设置
    getHeadName(type) {
      const { allotSetting = {} } = this.planTask || {}
      const { executorName = '', allotType = '', executorStaffId } = allotSetting || {}
      let createUserName = ''

      if(isOpenData && allotType == 'normal') {
        return <open-data type="userName" openid={executorStaffId}></open-data>
      }
      
      if (allotType == 'normal') {
        createUserName = executorName
      } else if (allotType == 'normal' && type === 'dispatchSettings') {
        createUserName = i18n.t('task.taskTypes.planTask.sendToPerson')
      } else if (allotType == 'pool') {
        createUserName = i18n.t('common.task.type.taskPool')
      } else if (allotType == 'auto') {
        createUserName = i18n.t('task.detail.components.autoAllot')
      } else if (allotType == 'waitDistribution') {
        createUserName = i18n.t('task.taskTypes.planTask.toBeAllot')
      }
      
      return createUserName
    },
    async getAddress() {
      try{
        const key = getCountryKey(this.task.taddress)
        const res = await addressKeyToViewLanguage(key, this.task.taddress)
        this.address = Filter.prettyAddress(res)
      }catch(err){}

    },
    getEndTime() {
      const { endSetting = {} } = this.planTask
      const { endBy = '', value = '' } = endSetting
      let endTime = ''
      
      if (endBy == 'times') {
        endTime = i18n.t('task.taskTypes.planTask.executeHowManyTime', {num: value})
      } else {
        endTime = formatDate(value, 'YYYY-MM-DD')
      }
      
      return endTime
    },
    // 获取归档工单数量
    getCount() {
      this.products.forEach(async (product, index) => {
        let params = {
          productId: product.id
        }
        let { code, message, result } = await getCount(params);
        if (code === 0) {
          this.$set(this.archiveCountArr, index, result.archiveCount)
        } else {
          this.$notify({
            title: this.$t('common.base.fail'),
            message,
            type: 'error'
          });
        }
      });
    },
    // 打开客户详情
    openCustomerView(openTaskTab) {
      // 需要确认权限
      // if (!this.allowOpenCustomerView) return;
      
      let fromId = window.frameElement.getAttribute('id');
      const customerId = this.task.customer.id;

      if(!customerId) return;

      let params = `noHistory=1`;

      if (openTaskTab) params += '&active=task';

      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params,
        fromId
      })
    },
    /** 
    * @description 打开产品详情
    */
    openProductView(productId) {
      this.$track.clickStat(this.$track.formatParams('CHECK_PRODUCT_TASK_NUM'));

      openTabForProductView(productId)
    },
    /** 
    * @description 获取关联的工单数量
    */
    getCountForCreate(params) {
      return TaskApi.getCountForCreate(params).then((result = {}) => {
        this.$set(this.productRelationCount, params.id, result);
      })
    },
    /** 
    * @description 是否显示产品关联的工单数量
    * 1. 全部数量>0
    * 2. 且未加密
    */
    showProductRelationCount(product) {
      let { id, name } = product;
      let { all } = this.productRelationCount[id] || {};
      return (Number(all) > 0 && !this.isEncryptField(name)) || this.archiveCount.length > 0 ;
    },
    /**
    * @description 是否加密字段
    */
    isEncryptField(value) {
      return value === ENCRYPT_FIELD_VALUE;
    },
    /** 
    * @description 产品
    */
    buildProducts() {
      let productsArr = [];
      let { products, product } = this.planTask.task || {};
      if (products && products.length) return products;
      if (product && product.id) return productsArr.push(product);
      
      return productsArr;
    },
    /** 
    * @description 处理产品关联字段数据
    */
    prettyRelationProductValue(value, index) {
      if (Array.isArray(value)) {
        return value[index];
      }

      return value;
    },
    // 获取创建方式的多语言label
    getSoureceLabel(key) {
      return TaskCreateMethodLabelEnum[key] || key
    },
  },
  created() {
    try {
      // 查询产品关联工单数量
      if (this.canSeeCustomer) {
        this.products.map(item => {
          this.$set(this.productRelationCount, item.id, { all: 0, unfinished: 0 });
          this.getCountForCreate({ module: 'product', id: item.id });
        })
      }
      this.getCount()
    } catch (error) {
      console.log(error);
    }
  },
  mounted(){
    this.getAddress()
  }
}
</script>
<style lang="scss">
.task-view-containner {
  .form-view-row-plantime {
    white-space: nowrap;
  }

  .icon-bianji1 {
    font-size: 14px;
  }

  .product-list {
    .product-item {
      &-name {
        line-height: 20px;
        display: flex;
        align-items: baseline;

        label {
          width: 98px;
          margin-bottom: 0;
          margin-right: 10px;
          // padding-left: 20px;
          color: $text-color-regular;
          // background: url(../../../../../../assets/img/task/product_icon.png) no-repeat left 4px;
          background-size: 12px;
        }

        span {
          margin-right: 0;
        }
      }

      &-relation {
        margin-top: 8px;
        padding: 6px 10px 6px 108px;
        // background-color: $bg-color-l3;
        // border-radius: $border-radius-base;

        .form-view {
          // background-color: $bg-color-l3;
        }
      }

      &:not(:last-child) {
        .product-item-name {
          margin-bottom: 8px;
        }

        .product-item-relation {
          margin-bottom: 16px;
        }
      }
    }
  }

  .synergies-name {
    margin-right: 12px;
  }
  .form-calendar-time {
    display: flex;
    align-items: center;
    >div{
      margin-right: 5px;
    }
    .iconfont {
      color: $color-primary;
    }
  }
}
</style>
